package com.andnnl.utils;

import java.io.IOException;

/**
 * Created by chenss on 2022/4/29.
 */
public class CutStringUtil {

    public static void main(String[] args) throws IOException {

        String str = "ab你好cd谢谢";
//        String str = "ab你好cd";
//        String str = " ";
        int len = str.getBytes("gbk").length;
        for (int x = 0; x < len+11; x++) {
            System.out.println("截取" + (x + 1) + "字节结果时："
                    + cutStringByGBK(str, x + 1));
        }
        String str1 = "ab你好cd杮";
        int len1 = str.getBytes("gbk").length;
        for (int x = 0; x < len1; x++) {
            System.out.println("截取" + (x + 1) + "字节结果时："
                    + cutStringByUTF8(str1, x + 1));
        }
    }

    // 使用UTF-8编码表进行截取字符串，一个汉字对应三个负数，一个英文字符对应一个正数
    public static String cutStringByUTF8(String str, int len) throws IOException {
        if(str==null){
            return null;
        }
        //前提不知道str他的长度，而指定的len长于实际str长度数组下标超过异常
//        int actualLen = str.getBytes("gbk").length;
        int actualLen = str.getBytes("utf-8").length;
        if(actualLen<len){
            len = actualLen;
        }
        byte[] buf = str.getBytes("utf-8");
        int count = 0;
        for (int x = len - 1; x >= 0; x--) {
            if (buf[x] < 0) {
                count++;
            } else {
                break;
            }
        }
        if (count % 3 == 0) {
            return new String(buf, 0, len, "utf-8");
        } else if (count % 3 == 1) {
            return new String(buf, 0, len - 1, "utf-8");
        } else {
            return new String(buf, 0, len - 2, "utf-8");
        }
    }

    // 使用GBK编码表进行字符串的截取，一个英文字符对应码表一个正数，一个汉字对应两个负数
    public static String cutStringByGBK(String str, int len)
            throws IOException {
        if(str==null){
            return null;
        }
        int actualLen = str.getBytes("gbk").length;
        if(actualLen<len){
            len = actualLen;
        }
        byte[] buf = str.getBytes("gbk");
        int count = 0;
        for (int x = len - 1; x >= 0; x--) {
            //统计按字节截取的字符串中，中文字符串有几个字节
            //小于0的是中文的部分
            if (buf[x] < 0) {
                count++;
            } else {
                break;
            }
        }
        if (count % 2 == 0) {
            return new String(buf, 0, len, "gbk");
        } else {
            return new String(buf, 0, len - 1, "gbk");
        }
    }
}
